package com.freecycle.sg.utils;

import java.io.File;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.freecycle.sg.sqlite.Freebie.Freebies;

/**
 * An assortment of UI helpers.
 */
public class UIUtils {

	private static final String TAG = "UIUtils";

	private static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss");
	private static SimpleDateFormat sdf2 = new SimpleDateFormat("MMM-dd-yyyy");

	public static boolean isHoneycomb() {
		// Can use static final constants like HONEYCOMB, declared in later
		// versions
		// of the OS since they are inlined at compile time. This is guaranteed
		// behavior.
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
	}

	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	public static boolean isHoneycombTablet(Context context) {
		return isHoneycomb() && isTablet(context);
	}

	public static long getCurrentTime(final Context context) {
		return System.currentTimeMillis();
	}

	public static Date parseDate(String dateString) {
		if (!TextUtils.isEmpty(dateString)) {
			try {
				return sdf.parse(dateString);
			} catch (ParseException e) {
				Log.e(TAG, e.toString());
			}
		}
		return null;
	}

	public static String formatDate(Date date) {
		if (date != null) {
			try {
				return sdf2.format(date);
			} catch (Exception e) {
				Log.w("formatDate", e);
			}
		}
		return "";
	}

	public static String addGroupingSeparator(int number) {
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
		dfs.setGroupingSeparator(new DecimalFormatSymbols()
				.getGroupingSeparator());

		DecimalFormat df = new DecimalFormat();
		df.setDecimalFormatSymbols(dfs);

		return df.format(number);
	}

	public static void toast(Context context, String message) {
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	public static void toastLong(Context context, String message) {
		Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	public static void toast(Context context, int textResId) {
		Toast.makeText(context, context.getResources().getString(textResId),
				Toast.LENGTH_SHORT).show();
	}

	public static void toastLong(Context context, int textResId) {
		Toast.makeText(context, context.getResources().getString(textResId),
				Toast.LENGTH_LONG).show();
	}

	public static boolean canMakeCall(Context context) {
		TelephonyManager mTelephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		int type = mTelephonyManager.getPhoneType();
		int simState = mTelephonyManager.getSimState();
		if (type == TelephonyManager.PHONE_TYPE_NONE) {
			return false;
		} else if (type == TelephonyManager.PHONE_TYPE_GSM
				&& simState == TelephonyManager.SIM_STATE_ABSENT) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Parse a list of strings into one universal string which elements
	 * separates by a comma
	 * 
	 * @param input
	 * @return
	 */
	public static String listToString(List<String> input) {
		StringBuilder builder = new StringBuilder();
		int size = input.size();
		for (int i = 0; i < size; i++) {
			if (i == size - 1) {
				builder.append(input.get(i));
			} else {
				builder.append(input.get(i)).append(",");
			}
		}
		return builder.toString();
	}

	/**
	 * Utility method to split a input string that separated by commas and/or
	 * whitespace.
	 * 
	 * @param input
	 * @return
	 */
	public static String[] splitString(String input) {
		Pattern p = Pattern.compile("[,\\s]+");
		String[] result = p.split(input);
		return result;
	}

	/**
	 * UI helper that help display an alert dialog box with predefined message
	 * with specified title
	 */
	public static void showDialog(Context context, String title, String message) {
		new AlertDialog.Builder(context)
				.setIcon(android.R.drawable.ic_dialog_alert).setTitle(title)
				.setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
	}

	/**
	 * UI helper that help display an alert dialog box with predefined message
	 */
	public static void showDialog(Context context, String message) {
		new AlertDialog.Builder(context)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setMessage(message)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
	}

	/**
	 * Method to create a temporary file for editting image purposes
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static File createTempFile(Context context) {
		final File path = new File(Environment.getExternalStorageDirectory(),
				File.separatorChar + "Android" + File.separatorChar + "data"
						+ File.separatorChar + context.getPackageName()
						+ File.separatorChar + "cache");
		if (!path.exists()) {
			path.mkdir();
		}
		return new File(path, "upload_image.tmp");
	}

	public static ContentValues buildFreebieCv(Cursor c) {
		ContentValues cv = new ContentValues();
		cv.put(Freebies.CATEGORY, c.getString(c.getColumnIndexOrThrow(Freebies.CATEGORY)));
		cv.put(Freebies.ADDED, c.getString(c.getColumnIndexOrThrow(Freebies.ADDED)));
		cv.put(Freebies.NAME, c.getString(c.getColumnIndexOrThrow(Freebies.NAME)));
		cv.put(Freebies.DESCRIPTION, c.getString(c.getColumnIndexOrThrow(Freebies.DESCRIPTION)));
		cv.put(Freebies.FORMATTED_ADDRESS, c.getString(c.getColumnIndexOrThrow(Freebies.FORMATTED_ADDRESS)));
		cv.put(Freebies.PHONE, c.getString(c.getColumnIndexOrThrow(Freebies.PHONE)));
		cv.put(Freebies.TITLE, c.getString(c.getColumnIndexOrThrow(Freebies.TITLE)));
		return cv;
	}
	
}
